#include "Monitor.h"

#include "Tools.h"

void
monitor_init (Monitor* obj)
{
        n_buffer_init (N_BUFFER (obj));
        object_set_destory_func (obj, monitor_destory);
        for (int i = 0; i < 8; ++i)
                obj->show[i] = 0x0d;
        obj->offset = 11;
        obj->dotpot = 0;
}

void
monitor_destruction (Monitor* obj)
{
        n_buffer_destruction (N_BUFFER (obj));
}

OBJECT_DEFINE_START (Monitor, monitor)

void
monitor_push (Monitor* obj)
{
        _digital_tube_push (obj->show);
}

/**
 * @brief 根据 NBuffer 父类中的缓冲判断此时的位移应该是多少。
 *
 * @param obj 本对象
 */
static void
monitor_load_offset (Monitor* obj)
{
        if (N_BUFFER (obj)->dotpot != 0x0) {
                obj->offset = 11;
                goto exit;
        }

        for (int i = 11; i >= 7; --i) {
                if (N_BUFFER (obj)->numbuf[i] != 0xd) {
                        obj->offset = i;
                        goto exit;
                }
        }
        obj->offset = 7;

exit:
        obj->dotpot = N_BUFFER (obj)->dotpot;
}

void
monitor_move_left (Monitor* obj)
{
        if (obj->offset > 7) {
                obj->offset -= 1;
                obj->dotpot -= 1;
        }
}

void
monitor_move_right (Monitor* obj)
{
        if (obj->offset < 11) {
                obj->offset += 1;
                obj->dotpot += 1;
        }
}

void
monitor_refresh_cache (Monitor* obj, bool is_reload_offset)
{
        uint8 offset, tmp;

        if (is_reload_offset)
                monitor_load_offset (obj);
        offset = obj->offset;

        for (int i = 8; i > 0; --i) {
                tmp              = N_BUFFER (obj)->numbuf[offset--];
                obj->show[i - 1] = code[tmp];
        }

        if (N_BUFFER (obj)->dotpot == 0x0)
                return;

        if (N_BUFFER (obj)->scibuf[3] == 0xc ||
            N_BUFFER (obj)->scibuf[3] == 0xb) {
                for (int i = 3; i >= 0; --i)
                        obj->show[i] = code[N_BUFFER (obj)->scibuf[i]];
        }
        /*根据 dotpot 打上小数点*/
        tmp = 8 - obj->dotpot;
        if (tmp < 8)
                obj->show[tmp] ^= 0x80;
}